package com.qf.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.util.SerializationUtils;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.Date;

/**
 * 存储对象到Redis服务
 * @author zjw
 */
public class Demo2 {



    @Test
    public void setValueByByteArray() throws JsonProcessingException {
        //1. Jedis连接Redis服务
        Jedis jedis = new Jedis("192.168.41.98",6379);

        //------------------操作------------------------------
        //2.1 准备对象
        User user = new User();
        user.setId(1);
        user.setName("娃哈哈哈哈哈哈哈哈");
        user.setBirthday(new Date());
        //2.2 通过Spring提供的工具类将user对象转为byte[]
        byte[] value = SerializationUtils.serialize(user);
        byte[] key = SerializationUtils.serialize("user");

        //2.3 存储
        jedis.setex(key,888888,value);

        //------------------------------------------------
        //3. 释放资源
        jedis.close();
    }


    @Test
    public void getByteArrayValueAsUser() throws JsonProcessingException {
        //1. Jedis连接Redis服务
        Jedis jedis = new Jedis("192.168.41.98",6379);

        //------------------操作------------------------------
        //2.1 设置key
        byte[] key = SerializationUtils.serialize("user");

        //2.2 获取byte[]对象
        byte[] value = jedis.get(key);

        //2.3 反序列化byte[]
        User user = (User) SerializationUtils.deserialize(value);
        System.out.println(user);

        //------------------------------------------------
        //3. 释放资源
        jedis.close();
    }


    @Test
    public void setValueByJSON() throws JsonProcessingException {
        //1. Jedis连接Redis服务
        Jedis jedis = new Jedis("192.168.41.98",6379);

        //------------------操作------------------------------
        //2.1 准备对象
        User user = new User();
        user.setId(1);
        user.setName("娃哈哈哈哈哈哈哈哈");
        user.setBirthday(new Date());
        //2.2 序列化为JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String value = objectMapper.writeValueAsString(user);
        //2.3 存储到Redis服务
        jedis.setex("user",9999999,value);

        //------------------------------------------------
        //3. 释放资源
        jedis.close();
    }


    @Test
    public void getValueAsUser() throws IOException {
        //1. Jedis连接Redis服务
        Jedis jedis = new Jedis("192.168.41.98",6379);

        //------------------操作------------------------------
        //2.1 获取JSON数据
        String value = jedis.get("user");
        //2.2 反序列化为User对象
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(value, User.class);
        System.out.println(user);
        //------------------------------------------------
        //3. 释放资源
        jedis.close();

    }
}
